<template>
    <div>
        <basic-container>
            <div class="app-container">
                <el-form :model="otherQuery" ref="queryForm" size="small" :inline="true">
                    <el-form-item label="工单名称">
                        <el-select style="width: 180px;" v-model="otherQuery.task_id" filterable remote reserve-keyword
                            placeholder="请输入关键词" :remote-method="querySearchAsync" :loading="loading" clearable
                            @clear="handleQuery">
                            <el-option v-for="item in restaurants" :key="item.task_id" :label="item.name"
                                :value="item.task_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="机种名称">
                        <el-select style="width: 180px;" v-model="otherQuery.aircraft_id" placeholder="请选择">
                            <el-option v-for="item in roleOptions" :key="item.aircraft_id" :label="item.aircraft"
                                :value="item.aircraft_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="设备名称">
                        <el-select style="width: 180px;" v-model="otherQuery.facility_id" placeholder="请选择" clearable>
                            <el-option v-for="item in menuList" :key="item.facility_id" :label="item.name"
                                :value="item.facility_id">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="产品SN">
                        <el-input style="width: 180px;" v-model="otherQuery.sequence" placeholder="请输入产品SN码"
                            clearable @keyup.enter="handleQuery" />
                    </el-form-item>
                    <!-- <el-form-item label="副码">
                        <el-input style="width: 180px;" v-model="otherQuery.code" placeholder="请输入副码" clearable />
                    </el-form-item> -->
                    <el-form-item label="日期查询">
                        <el-date-picker style="width: 250px;" v-model="value" clearable type="daterange"
                            value-format="yyyy-MM-dd" range-separator="至" start-placeholder="开始日期"
                            end-placeholder="结束日期">
                        </el-date-picker>
                        <el-button style="margin-left: 20px;" type="primary" icon="el-icon-search" size="mini"
                            @click="handleQuery">搜索</el-button>
                    </el-form-item>
                </el-form>
                <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="el-icon-download" size="mini"
                            @click="handleExport">导出</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="primary" plain size="mini" @click="handleCpk">计算cpk</el-button>
                    </el-col>
                </el-row>
                <template>
                    <el-table :data="expandedTableData" v-loading="loading" element-loading-text="拼命加载中"
                        element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)"
                        ref="table" style="width: 100%" border
                        :span-method="objectSpanMethod"
                        >
                        
                        <!-- 左侧固定列 -->
                        <el-table-column prop="f_name" label="工单名称" align="center" fixed="left" width="260">
                            <template slot-scope="scope">
                                <div style="display: flex; align-items: center; justify-content: center;">
                                    <!-- 展开/折叠按钮 -->
                                    <el-button 
                                        v-if="scope.row.isFirstRow && scope.row.hasMoreData"
                                        @click="toggleExpand(scope.row.sequence)"
                                        class="expand-btn"
                                        size="mini"
                                        style="margin-right: 5px;">
                                        <i :class="scope.row.isExpanded ? 'el-icon-minus' : 'el-icon-plus'" 
                                           style="font-size: 12px;"></i>
                                    </el-button>
                                    <span>{{ scope.row.f_name }}</span>
                                    <span v-if="scope.row.isFirstRow && scope.row.hasMoreData" 
                                          style="font-size: 12px; color: #999; margin-left: 5px;">
                                        ({{ scope.row.isExpanded ? scope.row.totalCount : 2 }}/{{ scope.row.totalCount }})
                                    </span>
                                </div>
                            </template>
                        </el-table-column>
                        
                        <el-table-column prop="sequence" label="产品sn" align="center" >
                            <template slot-scope="scope">
                                <div>{{ scope.row.sequence }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="f_status" label="产品状态" align="center"  >
                            <template slot-scope="scope">
                                <div>{{ scope.row.f_status }}</div>
                            </template>
                        </el-table-column>

                        <!-- 右侧设备信息列 -->
                        <el-table-column prop="ft_name" label="设备" align="center" >
                            <template slot-scope="scope">
                                <div>{{ scope.row.ft_name || '-' }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="fdt_time" label="时间" align="center">
                            <template slot-scope="scope">
                                <div>{{ scope.row.fdt_time || '-' }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="key" label="测试项" align="center" >
                            <template slot-scope="scope">
                                <div>{{ scope.row.key || '-' }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="floor" label="下限" align="center" >
                            <template slot-scope="scope">
                                <div>{{ scope.row.floor || '无' }}</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="value" label="实际值" align="center" >
                            <template slot-scope="scope">
                                <div v-if="scope.row.value !== undefined">
                                    
                                    {{ scope.row.value }}
                                </div>
                                <div v-else>-</div>
                            </template>
                        </el-table-column>

                        <el-table-column prop="upper" label="上限" align="center" >
                            <template slot-scope="scope">
                                <div>{{ scope.row.upper || '无' }}</div>
                            </template>
                        </el-table-column>

                    </el-table>
                </template>

            </div>
            <pagination v-show="toNum > 0" :total="toNum" :page.sync="otherQuery.index" :limit.sync="otherQuery.size"
                @pagination="gitMeassList" />
        </basic-container>
        <el-dialog title="cpk计算" :visible.sync="CpkdialogVisible" width="80%">
            <div style="display: flex;">
                <div v-for="(item, index) in Cpklist" :key="index">
                    <div style="margin:0 20px;text-align: center;">
                        <div style="margin: 5px 0;">{{ item.key }}</div>
                        <div>{{ item.value }}</div>
                    </div>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="CpkdialogVisible = false">取 消</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    getkindList,
    getdetails,
    getdkind,
    getdTaskkind,
    getCpk
} from "@/api/mainsn";

export default {
    data() {
        return {
            tableTile: ['机种名称', '产品编码'],
            CpkdialogVisible: false,
            Cpklist: [],
            checked: false,
            roleOptions: [],
            cpkNumbe: 1,
            NubIndex: null,
            produInd: null,
            tabPosition: "left",
            tableData: [],
            propObj: {
                multiple: true,
                value: "mark",
                label: "label",
                children: "children",
            },
            loading: false,
            towLad: false,
            showSearch: true,
            value1: [],
            total: 1,
            inMess: [],
            menuList: [],
            options: [
                {
                    value: "1",
                    label: "生效中",
                },
                {
                    value: "2",
                    label: "禁用",
                },
                {
                    value: "3",
                    label: "审核中",
                },
            ],
            // 弹出层标题
            title: "",
            open: false,
            toNum: 0,
            isExpandAll: false,
            restaurants: [],
            activeName: null,
            refreshTable: true,
            otherQuery: {
                facility_id: null,
                task_id: null,
                aircraft_id: null,
                start: null,
                finish: null,
                sequence: null,
                code: null,
                index: 1,
                size: 10,
            },
            expandedStates: {}, // 管理展开状态
            queryParams: {
                index: 1,
                size: 10,
            },
            value: null,
            form: {},
            rules: {
                role: [
                    { required: true, message: "角色名称不能为空", trigger: "blur" },
                ],
                describe: [
                    { required: true, message: "角色描述不能为空", trigger: "blur" },
                ],
            },
        };
    },
    created() {

    },
    computed: {
        expandedTableData() {
            const result = [];
            this.tableData.forEach((item) => {
                if (item.f_station && item.f_station.length > 0) {
                    // 获取该产品的展开状态
                    const isExpanded = this.expandedStates[item.sequence] || false;
                    // 如果数据超过2条且未展开，只显示前2条
                    const stationsToShow = item.f_station.length > 2 && !isExpanded 
                        ? item.f_station.slice(0, 2) 
                        : item.f_station;
                    
                    stationsToShow.forEach((station, stationIndex) => {
                        result.push({
                            // 基本信息
                            f_name: item.f_name,
                            sequence: item.sequence,
                            f_status: item.f_status,
                            aircraft: item.aircraft,
                            f_orders: item.f_orders,
                            // 设备信息
                            ft_name: station.ft_name,
                            ft_serial: station.ft_serial,
                            fdt_time: station.fdt_time,
                            fdt_status: station.fdt_status,
                            fdt_num: station.fdt_num,
                            key: station.key,
                            value: station.value,
                            floor: station.floor,
                            upper: station.upper,
                            isBoole: station.isBoole || false,
                            // 展开相关信息
                            isFirstRow: stationIndex === 0,
                            hasMoreData: item.f_station.length > 2,
                            isExpanded: isExpanded,
                            totalCount: item.f_station.length,
                            currentIndex: stationIndex
                        });
                    });
                } else {
                    // 如果没有设备信息，只显示基本信息
                    result.push({
                        f_name: item.f_name,
                        sequence: item.sequence,
                        f_status: item.f_status,
                        aircraft: item.aircraft,
                        f_orders: item.f_orders,
                        ft_name: null,
                        ft_serial: null,
                        fdt_time: null,
                        fdt_status: null,
                        fdt_num: null,
                        key: null,
                        value: null,
                        floor: null,
                        upper: null,
                        isBoole: false,
                        isFirstRow: true,
                        hasMoreData: false,
                        isExpanded: false,
                        totalCount: 0,
                        currentIndex: 0
                    });
                }
            });
            return result;
        }
    },

    mounted() {
        function formatDate(date) {
            const year = date.getFullYear();
            const month = (date.getMonth() + 1).toString().padStart(2, '0');
            const day = date.getDate().toString().padStart(2, '0');
            return `${year}-${month}-${day}`;
        }
        // 获取今天的日期
        const today = new Date();
        // 获取前三个月的日期
        const threeMonthsAgo = new Date(today);
        threeMonthsAgo.setMonth(today.getMonth() - 3);
        // 格式化日期为 "yyyy-MM-dd"
        const formattedToday = formatDate(today);
        const formattedThreeMonthsAgo = formatDate(threeMonthsAgo);
        this.queryParams.start = formattedThreeMonthsAgo
        this.queryParams.finish = formattedToday
        this.value = [formattedThreeMonthsAgo, formattedToday]
        this.getList()
        this.getdkindList();

    },
    methods: {
        getList() {
            getkindList(this.queryParams).then((response) => {
                this.menuList = response.data.data;
                console.log(this.menuList,"99999999999");
                this.firstQuery()
            });
        },

        handleCpk() {
            // 检查是否有选中的数据
            const selectedData = this.expandedTableData.filter(item => item.isBoole && item.value !== null);
            
            if (selectedData.length === 0) {
                return this.$message.error('请先选择要计算的数据');
            } else {
                let newdata = [];
                let processedKeys = {};
                
                selectedData.forEach(item => {
                    if (!processedKeys[item.key]) {
                        processedKeys[item.key] = true;
                        newdata.push({ key: item.key, values: [item.value] });
                    } else {
                        let existingEntry = newdata.find(el => el.key === item.key);
                        if (existingEntry) {
                            existingEntry.values.push(item.value);
                        }
                    }
                });

                let newArr = {
                    'data': newdata
                }
                getCpk(newArr).then((res => {
                    this.Cpklist = res.data.data
                    this.CpkdialogVisible = true
                })
                )
            }
        },

        handleExport() {
            this.$confirm('是否将数据导出为EXcel文档？').then(() => {
                const params = new URLSearchParams();
                this.value == null ? '' : params.append('start', this.value[0]);
                this.value == null ? '' : params.append('finish', this.value[1]);
                this.otherQuery.sequence == null ? '' : params.append('sequence', this.otherQuery.sequence);
                this.otherQuery.aircraft_id == null ? '' : params.append('aircraft_id', this.otherQuery.aircraft_id);
                this.otherQuery.facility_id == null ? '' : params.append('facility_id', this.otherQuery.facility_id);
                this.otherQuery.task_id == null ? '' : params.append('task_id', this.otherQuery.task_id);
                const url = new URL('http://192.168.20.252:8080/api/query/station/output');
                url.search = params.toString();
                window.location.href = url.toString();
            })
        },
        firstQuery() {
            (this.otherQuery = {
                facility_id: null,
                task_id: null,
                aircraft_id: null,
                start: null,
                finish: null,
                sequence: null,
                code: null,
                index: 1,
                size: 10,
            }),
                this.otherQuery.start = this.value == null ? null : this.value.length > 0 ? this.value[0] : null
            this.otherQuery.finish = this.value == null ? null : this.value.length > 0 ? this.value[1] : null
            this.gitMeassList();
        },
        gitMeassList() {
            this.otherQuery.start = this.value == null ? null : this.value.length > 0 ? this.value[0] : null
            this.otherQuery.finish = this.value == null ? null : this.value.length > 0 ? this.value[1] : null
            this.loading = true;
            this.tableData = []
            // 重置展开状态
            this.expandedStates = {};
            
            getdetails(this.otherQuery).then((res) => {
      
                this.tableData = res.data.data;
                if (this.tableData.length == 0) {
                    this.tableData = []
                    this.loading = false;
                } else {
                    // 处理新数据格式，为f_station中的每项添加isBoole属性
                    this.tableData.forEach(item => {
                        if (item.f_station && item.f_station.length > 0) {
                            item.f_station.forEach(station => {
                                this.$set(station, 'isBoole', false)
                            });
                        }
                    });
                    console.log(this.tableData);
                    this.toNum = res.data.total;
                    this.loading = false;
                }

            });
        },
        handleQuery() {
            // 重置到第一页
            this.otherQuery.index = 1;
            // 重置展开状态
            this.expandedStates = {};
            
            this.value = this.value == null ? [] : this.value;
            let queryData = {
                start: this.value.length > 0 ? this.value[0] : null,
                finish: this.value.length > 0 ? this.value[1] : null,
                facility_id: this.otherQuery.facility_id,
                task_id: this.otherQuery.task_id,
                aircraft_id: this.otherQuery.aircraft_id,
                sequence: this.otherQuery.sequence,
                code: this.otherQuery.code,
                index: this.otherQuery.index,
                size: this.otherQuery.size,
            };
            getdetails(queryData).then((res) => {
                this.tableData = res.data.data;
                if (this.tableData.length == 0) {
                    this.tableData = []
                    this.loading = false;
                } else {
                    // 处理新数据格式，为f_station中的每项添加isBoole属性
                    this.tableData.forEach(item => {
                        if (item.f_station && item.f_station.length > 0) {
                            item.f_station.forEach(station => {
                                this.$set(station, 'isBoole', false)
                            });
                        }
                    });
                }
                
                this.toNum = res.data.total;
            });
            this.loading = false;
        },

        getdkindList() {
            getdkind().then((res) => {
                this.roleOptions = res.data.data;
                console.log(this.roleOptions, '99999');
            });
        },

        // 切换展开/折叠状态
        toggleExpand(sequence) {
            this.$set(this.expandedStates, sequence, !this.expandedStates[sequence]);
        },
        
        objectSpanMethod({ row, rowIndex, columnIndex }) {
            // 合并左侧的基本信息列（工单名称、产品编码、产品状态）
            if (columnIndex === 0 || columnIndex === 1 || columnIndex === 2) {
                const currentSequence = row.sequence;
                const data = this.expandedTableData;
                
                // 找到相同sequence的行
                const sameSequenceRows = [];
                for (let i = 0; i < data.length; i++) {
                    if (data[i].sequence === currentSequence) {
                        sameSequenceRows.push(i);
                    }
                }
                
                const firstIndex = sameSequenceRows[0];
                const count = sameSequenceRows.length;
                
                // 如果当前行是该sequence的第一行，返回rowspan
                if (rowIndex === firstIndex) {
                    return {
                        rowspan: count,
                        colspan: 1
                    };
                } else if (sameSequenceRows.includes(rowIndex)) {
                    // 如果不是第一行但属于同一sequence，隐藏该单元格
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
            }
        },
        
        querySearchAsync(queryString) {
            if (queryString == null) return;

            let quey = {
                name: queryString,
            };
            getdTaskkind(quey).then((res) => {
                this.restaurants = res.data.data;
            });
        },
    },
};
</script>

<style lang="scss" scoped>
.message {
    width: 198%;
    background: #f8f8f9;
    display: flex;
    overflow-x: scroll;
}

.activeClass {
    color: red;
}

/* 展开按钮样式 */
.expand-btn {
    padding: 2px 4px !important;
    min-height: 20px !important;
    border: 1px solid #ddd;
    border-radius: 3px;
    background: #f8f9fa;
    
    &:hover {
        background: #e9ecef;
        border-color: #999;
    }
    
    i {
        color: #666;
        font-weight: bold;
    }
}
</style>